package com.example.yskjproject.view;

import android.content.Context;
import android.graphics.Point;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.yskjproject.R;

public class ToastFormat {
    private Context context;
    private TextView tipsText;
    private Toast toast = null;
    private static final int ContentID = R.id.ErrorTips;
    private static final int LayoutID = R.layout.dialog_toast;

    public ToastFormat(Context context) {
        this.context = context;
    }

    public void InitToast() {
        if (toast == null) {
            toast = new Toast(context);
            View view = LayoutInflater.from(context).inflate(LayoutID, null, false);

            // 修改 View 的宽度为屏幕宽度的三分之一
            modifyViewWidth(view, getScreenWidthThird());

            tipsText = view.findViewById(ContentID);
            toast.setView(view);
        }
    }

    private int getScreenWidthThird() {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int screenWidth = size.x;
        return screenWidth / 3;
    }

    private void modifyViewWidth(View view, int width) {
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) view.getLayoutParams();
        if (layoutParams == null) {
            layoutParams = new FrameLayout.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT);
        } else {
            layoutParams.width = width;
        }
        view.setLayoutParams(layoutParams);
    }

    public void setGravity(int gravity) {
        toast.setGravity(gravity, 0, 0);
    }

    public void setText(String tips) {
        tipsText.setText(tips);
    }

    public void show() {
        toast.show();
    }

    public void setShowTime(int time) {
        toast.setDuration(time);
    }

    public void setTextColor(int color) {
        tipsText.setTextColor(context.getResources().getColor(color));
    }

    public void setTextSize(float size) {
        tipsText.setTextSize(size);
    }
}
